package com.endava.listener;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class MyContextListener implements ServletContextListener {

	public void contextInitialized(ServletContextEvent servletContextEvent) {

		ServletContext context = servletContextEvent.getServletContext();
		String dataSourceUrl = context.getInitParameter("dataSourceUrl");
		String username = context.getInitParameter("userMySQL");
		String password = context.getInitParameter("passMySQL");

		try {
			Class.forName("com.mysql.jdbc.Driver").newInstance();
		} catch (Exception e) {
			System.out.println("Unable to load driver: " + e.getMessage());
		}
		Connection result = null;
		try {
			result = DriverManager.getConnection(dataSourceUrl, username,
					password);
		} catch (SQLException e) {
			System.out.println("Unable to get connect: " + e.getMessage());
		}

		context.setAttribute("connection", result);
	}

	public void contextDestroyed(ServletContextEvent servletContextEvent) {
		ServletContext context = servletContextEvent.getServletContext();
		Connection connection = (Connection) context.getAttribute("connection");
		if (connection != null) {
			try {
				connection.close();
			} catch (SQLException e) {
				System.out.println("Unable to close connection "
						+ e.getMessage());
			}
		}
	}
}
